package neu.soft.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import neu.soft.constant.PurchaseOrderType;
import neu.soft.entity.*;
import neu.soft.exception.AppException;
import neu.soft.exception.AppExceptionCodeMsg;
import neu.soft.feignclient.WarehouseFeignClient;
import neu.soft.mapper.PurchaseOrderMapper;
import neu.soft.query.BasePageQuery;
import neu.soft.service.SupplyService;
import neu.soft.service.WarehouseService;
import neu.soft.util.TypeConvert;
import neu.soft.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;


@Service
public class SupplyServiceImpl implements SupplyService {

    @Autowired
    PurchaseOrderMapper purchaseOrderMapper;

    @Autowired
    WarehouseService warehouseService;

    @Autowired
    WarehouseFeignClient warehouseFeignClient;

    //插入购货单
    @Override
    public int addPurchaseOrder(OperationPurchaseOrder purchaseOrder) {
        int res = purchaseOrderMapper.addPurchaseOrder(purchaseOrder);
        if (res < 1) {
            throw new AppException(AppExceptionCodeMsg.DZYJ_NGDZ);
        }
        return purchaseOrder.getPurchaseOrderId();
    }

    //通过购货单id查找
    @Override
    public OperationPurchaseOrder findById(Integer purchaseOrderId) {
        return purchaseOrderMapper.findById(purchaseOrderId);
    }

    //根据缺货单生成初步购货单
    @Override
    public OperationPurchaseOrder generatePurchaseOrder(String orderId, List<GoodInfo> goodInfoList, Vendor vendor, BigDecimal totalPrice, String type) {
        if (goodInfoList == null) {
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }
        OperationPurchaseOrder operationPurchaseOrder = new OperationPurchaseOrder();
        if (vendor != null) {
            //设置供应商信息
            operationPurchaseOrder.setVendor(vendor.getVendorName());
            operationPurchaseOrder.setVendorContactPerson(vendor.getVendorContactPerson());
            operationPurchaseOrder.setVendorContact(vendor.getVendorContact());
        }
        if (orderId != null || !"".equals(orderId)) {
            //设置缺货单号和设置总金额
            operationPurchaseOrder.setOrderId(orderId);
        }
        operationPurchaseOrder.setPurchasePrice(totalPrice);
        //设置购货单类型
        operationPurchaseOrder.setPurchaseType(type);
        //设置商品信息
        operationPurchaseOrder.setGoodInfoList(goodInfoList);
        return operationPurchaseOrder;
    }

    //缺货检查，通过比较购货量和现存库存量+预警值的大小判断是否缺货
    @Override
    public boolean checkShortage(List<NormalOrderInfo> normalOrderInfoList, List<Inventory> inventoryList, int alertValue) {
        long countRes = inventoryList.stream()
                .filter(inventory -> normalOrderInfoList.stream()
                        .filter(normalOrderInfo -> normalOrderInfo.getShoppingCode().equals(inventory.getCode()))
                        .anyMatch(normalOrderInfo -> (normalOrderInfo.getShoppingNum()+alertValue) <= inventory.getNum()))
                .count();
        return countRes < 1;
    }

    //批量插入商品信息
    @Override
    public void batchInsertGoodInfo(List<GoodInfo> goodInfoList) {
        purchaseOrderMapper.batchInsertGoodInfo(goodInfoList);
    }

    //完善购货单，将购货单和商品信息绑定
    @Override
    public OperationPurchaseOrder finishPurchaseOrder(OperationPurchaseOrder operationPurchaseOrder) {
        //获取购货单id，因为是自增id
        Integer purchaseOrderId = operationPurchaseOrder.getPurchaseOrderId();
        List<GoodInfo> goodInfoList = operationPurchaseOrder.getGoodInfoList();
        //设置id给商品信息
        for (GoodInfo gio : goodInfoList
        ) {
            gio.setGoodOrderId(purchaseOrderId);//为内置的商品信息设置绑定的购货单号
        }
        operationPurchaseOrder.setGoodInfoList(goodInfoList);
        return operationPurchaseOrder;
    }

    //分页查询购货单
    @Override
    public PageBean<OperationPurchaseOrder> findByPage(BasePageQuery query) {

        PageBean<OperationPurchaseOrder> pageBean = new PageBean<>();
        PageHelper.startPage(query.getPageNow(), query.getPageSize());
        List<OperationPurchaseOrder> purchaseOrdersList = purchaseOrderMapper.findByPage(query);
        purchaseOrdersList.forEach(operationPurchaseOrder -> {
            String type = TypeConvert.enumToString(PurchaseOrderType.class,operationPurchaseOrder.getPurchaseType());
            operationPurchaseOrder.setPurchaseType(type);
        });//类型转换
        PageInfo<OperationPurchaseOrder> pageInfo = new PageInfo<>(purchaseOrdersList);
        pageInfo.setTotal(purchaseOrdersList.size());//联表查询会让数据数量有误差，这里重新set进数目
        pageBean.setTotalRows(pageInfo.getTotal());
        pageBean.setTotalPages(pageInfo.getPages());
        pageBean.setRowData(pageInfo.getList());
        return pageBean;
    }

    //复用计算总金额
    @Override
    public BigDecimal getTotalPrice(List<GoodInfo> goodInfoList) {

        BigDecimal totalPrice = new BigDecimal("0.00");
        //计算购货总金额
        for (GoodInfo goodInfo : goodInfoList
        ) {
            int count = goodInfo.getGoodCount();
            BigDecimal temp = goodInfo.getPrice().multiply(new BigDecimal(count));
            totalPrice = totalPrice.add(temp);
        }
        //设置精度，并四舍五入
        totalPrice.setScale(2, BigDecimal.ROUND_HALF_UP);//计算总金额
        return totalPrice;
    }

    @Override
    public List<String> getType() {
        return TypeConvert.getTypeList(PurchaseOrderType.class);
    }


}
